package com.qsl.juc.alternately_print;

/**
 * 不放弃 cpu，没有用户态与内核态的切换
 */
public class AlternatelyPrintCas {

    enum ReadyToRun {
        T1, T2
    }

    private static volatile ReadyToRun READY_TO_RUN = ReadyToRun.T1;

    public static void main(String[] args) {
        char[] digitalArr = "1234567".toCharArray();
        char[] letterArr = "ABCDEFG".toCharArray();

        new Thread(() -> {
            for (char digital : digitalArr) {
                // 为什么不能是 while (READY_TO_RUN == ReadyToRun.T1){打印 digital 并修改 READY_TO_RUN}
                while (READY_TO_RUN != ReadyToRun.T1) {
                }     // cas自旋
                System.out.print(digital);
                READY_TO_RUN = ReadyToRun.T2;
            }
        }, "t1").start();

        new Thread(() -> {
            for (char letter : letterArr) {
                // 为什么不能是 while (READY_TO_RUN == ReadyToRun.T2){打印 letter 并修改 READY_TO_RUN}
                while (READY_TO_RUN != ReadyToRun.T2) {
                }     // cas自旋
                System.out.print(letter);
                READY_TO_RUN = ReadyToRun.T1;
            }
        }, "t2").start();
    }
}
